import moment from 'moment'
// import { App, DirectiveBinding } from 'vue'

type ElementType = HTMLElement & { __timer: NodeJS.Timer }

export const friendlyTime = (time: string): string => {
  return friendlyTimeWithOffset(time).str
}

const friendlyTimeWithOffset = (
  time: string
): { str: string; offset: number } => {
  const date = new Date(time)
  const value = Math.floor(date.getTime() / 1000)
  const now = new Date()
  const nowValue = Math.floor(now.getTime() / 1000)
  let str: string
  const offset = nowValue - value > 0 ? nowValue - value : 0
  if (offset < 60) {
    str = `${offset}秒前`
  } else if (offset < 60 * 60) {
    str = `${Math.floor(offset / 60)}分钟前`
  } else if (offset < 60 * 60 * 24) {
    str = `${Math.floor(offset / (60 * 60))}小时前`
  } else if (offset < 60 * 60 * 24 * 7) {
    const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    str = weeks[date.getDay()]
  } else if (date.getFullYear() === now.getFullYear()) {
    str = `${date.getMonth() + 1}月${date.getDate()}日`
  } else {
    str = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
  }
  return {
    str,
    offset,
  }
}
const mounted = (el: ElementType, binding: any) => {
  const value = binding.value
  const result = friendlyTimeWithOffset(value)
  el.innerHTML = result.str

  el.style.minWidth = el.getBoundingClientRect().width + 'px'
  el.onmouseover = () => {
    el.innerHTML = moment(value).format('YYYY-MM-DD HH:mm:ss')
  }
  el.onmouseout = () => {
    const result = friendlyTimeWithOffset(value)
    el.innerHTML = result.str
  }
  if (result.offset <= 60 * 60) {
    el.__timer = setInterval(() => {
      const result = friendlyTimeWithOffset(value)
      el.innerHTML = result.str
      if (result.offset > 60 * 60) {
        clearInterval(el.__timer)
      }
    }, 30000)
  }
}

export default {
  install: (app: any) => {
    let mount = (el, binding) => {
      mounted(el, binding)
    }
    app.directive('time', {
      update: mount,
      updated: mount,
      mounted: mount,
      bind: mount,
      unbind(el: ElementType) {
        clearInterval(el.__timer)
      },
      unmounted(el: ElementType) {
        clearInterval(el.__timer)
      },
    })
  },
}
